<script setup>
import { ref, computed, onMounted } from 'vue'
import { useStore } from 'vuex'
import { ElForm, ElFormItem, ElButton, ElTable, ElTableColumn, ElMessage, ElDatePicker, ElSelect, ElOption, ElUpload, ElDialog, ElInput } from 'element-plus'
import { UploadFilled } from '@element-plus/icons-vue'
import axios from 'axios'

const store = useStore()

// 响应式变量
const loading = ref(false)
const tableLoading = ref(false)
const selectedSession = ref(null)
const queryParams = ref({
  classroom: '',
  dateRange: null
})
// 分页相关变量
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const importDialogVisible = ref(false)
const importResultVisible = ref(false)
const importResult = ref({
  totalRows: 0,
  successRows: 0,
  failedRows: 0,
  errorMessage: ''
})

// 计算属性
const historicalSessions = computed(() => store.state.historicalSessions)

// 格式化时间
const formatTime = (date) => {
  if (!date) return ''
  const d = new Date(date)
  return d.toLocaleString('zh-CN')
}

const formatDate = (date) => {
  if (!date) return ''
  const d = new Date(date)
  const year = d.getFullYear()
  const month = String(d.getMonth() + 1).padStart(2, '0')
  const day = String(d.getDate()).padStart(2, '0')
  return `${year}年${month}月${day}日`
}

// 查询历史签到会话
const queryHistoricalSessions = async () => {
  loading.value = true;
  try {
    // 构建查询参数
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value
    };
    
    if (queryParams.value.classroom) {
      params.classroom = queryParams.value.classroom;
    }
    
    // 如果有日期范围，则添加到查询参数
    if (queryParams.value.dateRange && queryParams.value.dateRange.length === 2) {
      params.startDate = queryParams.value.dateRange[0];
      params.endDate = queryParams.value.dateRange[1];
    }
    
    const result = await store.dispatch('queryHistoricalSessions', params);
    // 更新总记录数
    if (result && result.total !== undefined) {
      total.value = result.total;
    }
  } catch (error) {
    ElMessage.error('查询历史签到会话失败：' + (error.message || '未知错误'));
  } finally {
    loading.value = false;
  }
}

// 查看历史会话记录
const viewHistoricalSessionRecords = async (session) => {
  if (!session || !session.id) {
    ElMessage.warning('无效的会话信息')
    return
  }
  
  tableLoading.value = true
  try {
    selectedSession.value = session
    await store.dispatch('getHistoricalSessionRecords', session.id)
  } catch (error) {
    ElMessage.error('获取历史签到记录失败：' + (error.message || '未知错误'))
  } finally {
    tableLoading.value = false
  }
}

// 返回会话列表
const returnToSessionList = () => {
  selectedSession.value = null
  // 清空签到记录
  store.commit('SET_SIGN_IN_RECORDS', [])
}

// 按教室筛选后的签到记录
const filteredSignInRecords = computed(() => {
  return store.state.signInRecords
})

// 导入Excel数据
const importExcelData = async (param) => {
  loading.value = true
  importDialogVisible.value = false
  
  try {
    // ElUpload组件传递的参数包含file属性，而非直接传递file对象
    const file = param.file
    const formData = new FormData()
    formData.append('file', file)
    
    const response = await axios({
      url: '/api/sign-in/import/data',
      method: 'POST',
      data: formData,
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
    
    const result = response.data
    importResult.value = result
    
    if (result.success) {
      ElMessage.success(`导入成功！总共${result.totalRows}行，成功${result.successRows}行，失败${result.failedRows}行`)
      // 重新查询历史会话
      await queryHistoricalSessions()
      // 显示导入结果详情
      importResultVisible.value = true
    } else {
      ElMessage.error('导入失败：' + result.message)
    }
  } catch (error) {
    ElMessage.error('导入失败，请稍后重试：' + (error.message || '未知错误'))
  } finally {
    loading.value = false
  }
  
  // 阻止自动上传完成后的事件传播
  return false
}

// 处理文件上传前的验证
const beforeUpload = (file) => {
  const isXlsx = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
  const isXls = file.type === 'application/vnd.ms-excel'
  const isValidFormat = isXlsx || isXls
  
  if (!isValidFormat) {
    ElMessage.error('请上传Excel格式的文件（.xlsx或.xls）')
    return false
  }
  
  return true
}

// 导出历史签到数据
const exportHistoricalData = async () => {
  if (historicalSessions.value.length === 0) {
    ElMessage.warning('没有可导出的数据')
    return
  }
  
  loading.value = true
  try {
    // 构建查询参数，与查询函数相同
    const params = {};
    
    if (queryParams.value.classroom) {
      params.classroom = queryParams.value.classroom;
    }
    
    if (queryParams.value.dateRange && queryParams.value.dateRange.length === 2) {
      // 转换日期为时间戳格式，确保后端能正确解析
      params.startDate = queryParams.value.dateRange[0].getTime();
      params.endDate = queryParams.value.dateRange[1].getTime();
    }
    
    // 发送导出请求，将POST改为GET并使用查询参数
    const response = await axios({
      url: '/api/sign-in/export/history',
      method: 'GET',
      params: params,
      responseType: 'blob'
    })
    
    // 创建下载链接
    const blob = new Blob([response.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `历史签到记录_${new Date().getTime()}.xlsx`
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
    
    ElMessage.success('数据导出成功')
  } catch (error) {
    ElMessage.error('导出失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 处理页码变化
const handleCurrentChange = (val) => {
  currentPage.value = val;
  queryHistoricalSessions();
}

// 处理每页条数变化
const handleSizeChange = (val) => {
  pageSize.value = val;
  currentPage.value = 1; // 重置为第一页
  queryHistoricalSessions();
}

// 页面加载时执行一次查询
onMounted(() => {
  queryHistoricalSessions()
})
</script>

<template>
  <div class="container">
    <div class="page-header">
      <h2>历史签到查询</h2>
    </div>
    
    <!-- 功能菜单 -->
    <div class="menu-bar" style="margin-bottom: 20px; display: flex; gap: 10px;">
      <router-link to="/teacher">
        <ElButton type="primary">当前签到管理</ElButton>
      </router-link>
      <router-link to="/teacher/history">
        <ElButton type="primary">历史签到查询</ElButton>
      </router-link>
    </div>
    
    <!-- 会话列表视图 -->
    <div v-if="!selectedSession" class="card" style="margin-bottom: 20px;">
      <h3>签到会话查询</h3>
      
      <ElForm :model="queryParams" label-width="120px" style="margin-bottom: 20px;">
        <div style="display: flex; gap: 20px; flex-wrap: wrap;">
          <ElFormItem label="日期范围">
            <ElDatePicker
              v-model="queryParams.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              style="width: 300px;"
            />
          </ElFormItem>
          
          <ElFormItem label="选择教室">
            <ElSelect v-model="queryParams.classroom" placeholder="请选择教室" style="width: 200px;">
              <ElOption label="全部教室" value="" />
              <ElOption label="东微机室" value="东微机室" />
              <ElOption label="西微机室" value="西微机室" />
            </ElSelect>
          </ElFormItem>
          
          <ElFormItem>
            <div style="display: flex; gap: 10px; align-items: center;">
              <ElButton type="primary" @click="queryHistoricalSessions" :loading="loading">
                查询
              </ElButton>
                            <ElButton 
                type="info" 
                @click="exportHistoricalData" 
                :loading="loading"
                :disabled="historicalSessions.length === 0"
              >
                导出数据
              </ElButton>
              <ElUpload
                action=""
                :before-upload="beforeUpload"
                :http-request="importExcelData"
                :auto-upload="true"
                :show-file-list="false"
              >
                <ElButton      
                  :loading="loading"
                  plain>
                  <UploadFilled style="margin-right: 1 px;" />
                  
                </ElButton>
              </ElUpload>

            </div>
          </ElFormItem>
        </div>
      </ElForm>
      
      <!-- 历史会话列表 -->
      <ElTable 
        :data="historicalSessions" 
        style="width: 100%" 
        :loading="loading"
        v-loading="loading"
        element-loading-text="加载中..."
      >
        <!-- <ElTableColumn prop="id" label="会话ID" width="80" /> -->
        <ElTableColumn prop="date" label="日期" width="150">
          <template #default="scope">
            {{ formatDate(scope.row.date) }}
          </template>
        </ElTableColumn>
        <ElTableColumn prop="className" label="班级" width="120" />
        <ElTableColumn prop="sectionNumber" label="节次" width="80" />
        <ElTableColumn prop="topic" label="课题" min-width="150" />
        <ElTableColumn prop="teacherName" label="教师" width="100" />
        <ElTableColumn prop="classroom" label="教室" width="100" />
        <!-- <ElTableColumn prop="createTime" label="创建时间" width="180">
          <template #default="scope">
            {{ formatTime(scope.row.createTime) }}
          </template>
        </ElTableColumn> -->
        <ElTableColumn prop="status" label="状态" width="80">
          <template #default="scope">
            <span v-if="scope.row.status === 0">未开始</span>
            <span v-else-if="scope.row.status === 1" style="color: #67c23a;">进行中</span>
            <span v-else-if="scope.row.status === 2" style="color: #909399;">已结束</span>
          </template>
        </ElTableColumn>
        <ElTableColumn label="操作" width="120">
          <template #default="scope">
            <ElButton 
              type="primary" 
              size="small" 
              @click="viewHistoricalSessionRecords(scope.row)"
            >
              查看记录
            </ElButton>
          </template>
        </ElTableColumn>
      </ElTable>
      
      <div v-if="historicalSessions.length === 0 && !loading" style="text-align: center; padding: 40px; color: #909399;">
        <p>暂无历史签到记录</p>
      </div>
      
      <!-- 分页组件 -->
      <div v-if="total > 0" style="margin-top: 20px; display: flex; justify-content: flex-end;">
        <ElPagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    
    <!-- 会话详情视图 -->
    <div v-if="selectedSession" class="card">
      <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
        <h3>历史签到详情</h3>
        <ElButton type="primary" @click="returnToSessionList">
          返回会话列表
        </ElButton>
      </div>
      
      <!-- 会话信息 -->
      <div class="session-info" style="margin-bottom: 20px; padding: 15px; background-color: #f5f7fa; border-radius: 4px;">
        <p><strong>日期：</strong>{{ formatDate(selectedSession.date) }}</p>
        <p><strong>班级：</strong>{{ selectedSession.className }}</p>
        <p><strong>节次：</strong>{{ selectedSession.sectionNumber }}</p>
        <p><strong>课题：</strong>{{ selectedSession.topic }}</p>
        <p><strong>教师姓名：</strong>{{ selectedSession.teacherName }}</p>
        <p><strong>教室：</strong>{{ selectedSession.classroom }}</p>
        <!-- <p><strong>创建时间：</strong>{{ formatTime(selectedSession.createTime) }}</p>
        <p><strong>开始时间：</strong>{{ formatTime(selectedSession.startTime) }}</p>
        <p><strong>结束时间：</strong>{{ formatTime(selectedSession.endTime) || '未结束' }}</p> -->
        <p><strong>状态：</strong>
          <span v-if="selectedSession.status === 0">未开始</span>
          <span v-else-if="selectedSession.status === 1" style="color: #67c23a;">进行中</span>
          <span v-else-if="selectedSession.status === 2" style="color: #909399;">已结束</span>
        </p>
      </div>
      
      <!-- 签到学生列表 -->
      <div class="card">
        <div style="margin-bottom: 20px;">
          <h3>签到学生列表（共{{ filteredSignInRecords.length }}人）</h3>
        </div>
        <ElTable 
          :data="filteredSignInRecords" 
          style="width: 100%" 
          :loading="tableLoading"
          v-loading="tableLoading"
          element-loading-text="加载中..."
        >
          <ElTableColumn prop="studentName" label="学生姓名" width="120" />
          <ElTableColumn prop="classroomLocation" label="教室位置" width="120" />
          <!-- <ElTableColumn prop="signInTime" label="签到时间" width="180">
            <template #default="scope">
              {{ formatTime(scope.row.signInTime) }}
            </template>
          </ElTableColumn> -->
        </ElTable>
      </div>
    </div>
    
    <!-- 导入结果对话框 -->
    <ElDialog 
      v-model="importResultVisible" 
      title="导入结果"
      width="600px"
    >
      <div class="import-result">
        <p><strong>总行数：</strong>{{ importResult.totalRows }}</p>
        <p><strong>成功行数：</strong>{{ importResult.successRows }}</p>
        <p><strong>失败行数：</strong>{{ importResult.failedRows }}</p>
        
        <div v-if="importResult.failedRows > 0" class="error-section">
          <h4>错误信息：</h4>
          <pre class="error-messages">{{ importResult.errorMessage }}</pre>
        </div>
      </div>
      
      <template #footer>
        <ElButton @click="importResultVisible = false">确定</ElButton>
      </template>
    </ElDialog>
  </div>
</template>

<style scoped>
.container {
  padding: 20px;
}

.page-header {
  margin-bottom: 30px;
}

.card {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 20px;
  margin-bottom: 20px;
}

.card h3 {
  margin-top: 0;
  margin-bottom: 20px;
  color: #303133;
  font-size: 18px;
  font-weight: 500;
}

.classroom-selector {
  margin-bottom: 20px;
}

.control-buttons {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
}

.session-info p {
  margin: 5px 0;
  color: #606266;
}

.session-info strong {
  color: #303133;
}
.import-result {
  font-size: 14px;
  line-height: 1.8;
}

.error-section {
  margin-top: 15px;
  padding: 10px;
  background-color: #fef0f0;
  border: 1px solid #fbc4c4;
  border-radius: 4px;
}

.error-section h4 {
  margin-top: 0;
  color: #f56c6c;
}

.error-messages {
  margin: 10px 0 0 0;
  padding: 10px;
  background-color: #fff;
  border: 1px solid #fbc4c4;
  border-radius: 4px;
  font-family: monospace;
  white-space: pre-wrap;
  word-break: break-all;
  max-height: 200px;
  overflow-y: auto;
  color: #606266;
}
</style>